package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistsException;
import com.atguigu.gulimall.member.exception.UsernameExistsException;
import com.atguigu.gulimall.member.vo.LoginUserVo;
import com.atguigu.gulimall.member.vo.RegisterUserVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据用户名和手机号注册用户
     * @param vo
     */
    @Override
    public void register(RegisterUserVo vo) {
        MemberEntity memberEntity=new MemberEntity();
        //验证用户名和手机号的合法性，如果数据库存在任何一项，则不允许注册，j校验异常向上抛出，由Controller捕获
        String username = vo.getUsername();
        isUniqueUsername(username);
        String phone = vo.getPhone();
        isUniquePhone(phone);
        memberEntity.setUsername(username);
        memberEntity.setNickname(username);
        memberEntity.setMobile(phone);
        //密码需加密，使用BCrypt进行加密，即使是相同的密码，每次加密的结果都是不一样的
        String encodePassword = new BCryptPasswordEncoder().encode(vo.getPassword());
        memberEntity.setPassword(encodePassword);
        //默认等级，默认是普通会员的id
        MemberLevelEntity levelEntity=memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setCreateTime(new Date());
        this.baseMapper.insert(memberEntity);
    }

    //校验用户名是否唯一
    @Override
    public void isUniqueUsername(String username) throws UsernameExistsException{
        //对于基本类型，要使用包装类接收，因为如果是基本类型，数据库没有数据，那么就会报错
        Integer count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count > 0){
            throw new UsernameExistsException();
        }
    }
    //校验手机号是否唯一
    @Override
    public void isUniquePhone(String phone) throws PhoneExistsException{
        Integer count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count > 0){
            throw new PhoneExistsException();
        }
    }

    /**
     * 普通用户登录，可以根据手机号或用户名进行登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(LoginUserVo vo) {
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getUserAccount()).or().eq("mobile", vo.getUserAccount()));
        if(memberEntity ==null){
           return null;
        }
        String savedPassword = memberEntity.getPassword();
        boolean matches = new BCryptPasswordEncoder().matches(vo.getPassword(), savedPassword);
        if(matches){
            return memberEntity;
        }else {
            return null;
        }
    }

    /**
     * 社交登录，用户通过设计平台进行登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo vo) {
        //1、根据用户的uid查询数据库使用该社交用户是否已经注册
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if(memberEntity != null){
            //如果有，更新用户信息
            MemberEntity update=new MemberEntity();
            update.setId(memberEntity.getId());
            //设置新的授权码
            update.setAccessToken(vo.getAccess_token());
            //设置新的过期时间
            update.setExpiresIn(vo.getExpires_in());
            this.baseMapper.updateById(update);
            //设置新的授权码和过期时间
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            //返回
            return memberEntity;
        }else {
            //如果没有，那么先注册
            MemberEntity register=new MemberEntity();
            try{
                Map<String,String> query=new HashMap<>();
                query.put("access_token",vo.getAccess_token());
                query.put("uid",vo.getUid());
                //向微博服务器获取用户信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com","/2/users/show.json", "get", new HashMap<String, String>(), query);
                if(response.getStatusLine().getStatusCode() == 200){
                    //获取成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1:0);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            //不管有没有查出用户信息，先向数据库保存uid、授权码、过期时间这些信息，下次直接更新数据就行，不需要再进行插入
            register.setSocialUid(vo.getUid());
            register.setAccessToken(vo.getAccess_token());
            register.setExpiresIn(vo.getExpires_in());
            //向数据库插入社交用户信息
            this.baseMapper.insert(register);
            //返回用户信息
            return register;
        }
    }

}